package com.WISSC.util.file;

import com.WISSC.util.date.DateUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author 张子艺
 * @packge com.xbxkj.util
 * @data 2019-05-21 15:26
 * @project GoodLuck
 */
public class DownLoadFileUtils {
    /**
     *
     * @param response  web输出流
     * @param url   文件地址
     * @param fileName  文件名称
     * @return
     */
    public static String downloadFile(HttpServletResponse response,String url,String fileName){
        File file = new File(url);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + DateUtil.date()+".png");
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "下载失败";
    }
}
